import React, { useEffect } from "react";
import { X, AlertCircle, Save } from "lucide-react";
import type { HealthRecord } from "@/services/health.service";
import { HEALTH_VALIDATION } from "@/lib/constants/health-validation";

interface HealthRecordFormProps {
  record: Partial<HealthRecord> & {
    recordType: HealthRecord["recordType"];
    details: HealthRecord["details"];
  };
  isCreating: boolean;
  error?: string;
  onClose: () => void;
  onChange: (record: Partial<HealthRecord>) => void;
  onSave: () => void;
  onError: (error: string) => void;
}

export function HealthRecordForm({
  record,
  isCreating,
  error,
  onClose,
  onChange,
  onSave,
  onError,
}: HealthRecordFormProps) {
  // 从本地存储加载草稿
  useEffect(() => {
    if (isCreating) {
      const draft = localStorage.getItem('healthRecordDraft');
      if (draft) {
        const parsedDraft = JSON.parse(draft);
        onChange(parsedDraft);
      }
    }
  }, [isCreating]);

  // 保存草稿
  const handleChange = (updatedRecord: Partial<HealthRecord>) => {
    onChange(updatedRecord);
    if (isCreating) {
      localStorage.setItem('healthRecordDraft', JSON.stringify(updatedRecord));
    }
  };

  // 清除草稿
  const handleClose = () => {
    localStorage.removeItem('healthRecordDraft');
    onClose();
  };

  // 添加验证函数
  function validateRecord(record: Partial<HealthRecord>): string | null {
    if (!record.recordType || !record.details) return "数据不完整";

    switch (record.recordType) {
      case "weight":
        if (!record.details.weight?.value) return "请输入体重";
        if (record.details.weight.value < HEALTH_VALIDATION.weight.min || 
            record.details.weight.value > HEALTH_VALIDATION.weight.max) {
          return HEALTH_VALIDATION.weight.message;
        }
        break;

      case "bloodPressure":
        if (!record.details.bloodPressure?.systolic || !record.details.bloodPressure?.diastolic) {
          return "请输入完整的血压数据";
        }
        if (record.details.bloodPressure.systolic < HEALTH_VALIDATION.bloodPressure.systolic.min || 
            record.details.bloodPressure.systolic > HEALTH_VALIDATION.bloodPressure.systolic.max) {
          return HEALTH_VALIDATION.bloodPressure.systolic.message;
        }
        if (record.details.bloodPressure.diastolic < HEALTH_VALIDATION.bloodPressure.diastolic.min || 
            record.details.bloodPressure.diastolic > HEALTH_VALIDATION.bloodPressure.diastolic.max) {
          return HEALTH_VALIDATION.bloodPressure.diastolic.message;
        }
        if (record.details.bloodPressure.pulse && 
            (record.details.bloodPressure.pulse < HEALTH_VALIDATION.bloodPressure.pulse.min || 
             record.details.bloodPressure.pulse > HEALTH_VALIDATION.bloodPressure.pulse.max)) {
          return HEALTH_VALIDATION.bloodPressure.pulse.message;
        }
        break;

      case "heartRate":
        if (!record.details.heartRate?.current) return "请输入心率";
        if (record.details.heartRate.current < HEALTH_VALIDATION.heartRate.min || 
            record.details.heartRate.current > HEALTH_VALIDATION.heartRate.max) {
          return HEALTH_VALIDATION.heartRate.message;
        }
        break;

      case "sleepQuality":
        if (!record.details.sleepQuality?.totalSleepDuration) return "请输入睡眠时长";
        if (record.details.sleepQuality.totalSleepDuration < HEALTH_VALIDATION.sleepQuality.min || 
            record.details.sleepQuality.totalSleepDuration > HEALTH_VALIDATION.sleepQuality.max) {
          return HEALTH_VALIDATION.sleepQuality.message;
        }
        break;
    }

    return null;
  }

  // 修改 onSave 处理函数
  const handleSave = () => {
    const validationError = validateRecord(record);
    if (validationError) {
      onError(validationError);
      return;
    }
    onSave();
  };

  // 渲染记录类型对应的表单字段
  const renderRecordFields = () => {
    switch (record.recordType) {
      case "weight":
        return (
          <div className="flex gap-4">
            <input
              type="number"
              step="0.1"
              min={HEALTH_VALIDATION.weight.min}
              max={HEALTH_VALIDATION.weight.max}
              className="flex-1 px-3 py-2 border rounded-lg bg-background"
              placeholder={`输入体重 (${HEALTH_VALIDATION.weight.min}-${HEALTH_VALIDATION.weight.max} kg)`}
              value={record.details?.weight?.value || ""}
              onChange={(e) => {
                const value = parseFloat(e.target.value);
                onChange({
                  ...record,
                  details: {
                    weight: {
                      value: isNaN(value) ? 0 : value,
                      unit: record.details?.weight?.unit || "kg",
                    },
                  },
                });
              }}
            />
            <select
              className="px-3 py-2 border rounded-lg bg-background"
              value={record.details?.weight?.unit || "kg"}
              onChange={(e) => {
                onChange({
                  ...record,
                  details: {
                    weight: {
                      value: record.details?.weight?.value || 0,
                      unit: e.target.value as "kg" | "lb",
                    },
                  },
                });
              }}
            >
              <option value="kg">kg</option>
              <option value="lb">lb</option>
            </select>
          </div>
        );

      case "bloodPressure":
        return (
          <div className="space-y-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <label className="block text-sm text-muted-foreground mb-1">收缩压</label>
                <input
                  type="number"
                  className="w-full px-3 py-2 border rounded-lg bg-background"
                  placeholder="60-200 mmHg"
                  value={record.details?.bloodPressure?.systolic || ""}
                  onChange={(e) => {
                    const value = parseInt(e.target.value);
                    onChange({
                      ...record,
                      details: {
                        bloodPressure: {
                          systolic: isNaN(value) ? 0 : value,
                          diastolic: record.details?.bloodPressure?.diastolic || 0,
                          pulse: record.details?.bloodPressure?.pulse,
                        },
                      },
                    });
                  }}
                />
              </div>
              <div className="flex-1">
                <label className="block text-sm text-muted-foreground mb-1">舒张压</label>
                <input
                  type="number"
                  className="w-full px-3 py-2 border rounded-lg bg-background"
                  placeholder="40-130 mmHg"
                  value={record.details?.bloodPressure?.diastolic || ""}
                  onChange={(e) => {
                    const value = parseInt(e.target.value);
                    onChange({
                      ...record,
                      details: {
                        bloodPressure: {
                          systolic: record.details?.bloodPressure?.systolic || 0,
                          diastolic: isNaN(value) ? 0 : value,
                          pulse: record.details?.bloodPressure?.pulse,
                        },
                      },
                    });
                  }}
                />
              </div>
            </div>
            <div>
              <label className="block text-sm text-muted-foreground mb-1">心率（可选）</label>
              <input
                type="number"
                className="w-full px-3 py-2 border rounded-lg bg-background"
                placeholder="40-200 次/分钟"
                value={record.details?.bloodPressure?.pulse || ""}
                onChange={(e) => {
                  const value = parseInt(e.target.value);
                  onChange({
                    ...record,
                    details: {
                      bloodPressure: {
                        systolic: record.details?.bloodPressure?.systolic || 0,
                        diastolic: record.details?.bloodPressure?.diastolic || 0,
                        pulse: isNaN(value) ? undefined : value,
                      },
                    },
                  });
                }}
              />
            </div>
          </div>
        );

      case "heartRate":
        return (
          <input
            type="number"
            className="w-full px-3 py-2 border rounded-lg bg-background"
            placeholder="40-200 次/分钟"
            value={record.details?.heartRate?.current || ""}
            onChange={(e) => {
              const value = parseInt(e.target.value);
              onChange({
                ...record,
                details: {
                  heartRate: {
                    current: isNaN(value) ? 0 : value,
                  },
                },
              });
            }}
          />
        );

      case "sleepQuality":
        return (
          <div className="space-y-4">
            <input
              type="number"
              step="0.5"
              className="w-full px-3 py-2 border rounded-lg bg-background"
              placeholder="0-24 小时"
              value={record.details?.sleepQuality?.totalSleepDuration || ""}
              onChange={(e) => {
                const value = parseFloat(e.target.value);
                onChange({
                  ...record,
                  details: {
                    sleepQuality: {
                      totalSleepDuration: isNaN(value) ? 0 : value,
                    },
                  },
                });
              }}
            />
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50">
      <div className="fixed left-[50%] top-[50%] translate-x-[-50%] translate-y-[-50%] w-full max-w-lg">
        <div className="bg-card rounded-lg p-6 shadow-xl">
          <div className="flex justify-between items-center mb-6">
            <div className="flex items-center gap-2">
              <Save className="w-5 h-5 text-primary" />
              <h2 className="text-xl font-bold">
                {isCreating ? "添加健康记录" : "编辑健康记录"}
              </h2>
            </div>
            <button
              onClick={handleClose}
              className="p-2 hover:bg-accent rounded-lg transition-colors"
              title="关闭"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          {error && (
            <div className="mb-6 p-4 text-sm text-destructive bg-destructive/10 rounded-lg flex items-center gap-2 animate-shake">
              <AlertCircle className="w-5 h-5 flex-shrink-0" />
              <p>{error}</p>
            </div>
          )}

          <div className="space-y-6">
            {/* 记录类型选择 */}
            <div>
              <label className="block text-sm font-medium mb-2">记录类型</label>
              <select
                value={record.recordType}
                onChange={(e) =>
                  onChange({ ...record, recordType: e.target.value as HealthRecord["recordType"] })
                }
                className="w-full px-3 py-2 border rounded-lg bg-background"
              >
                <option value="weight">体重</option>
                <option value="bloodPressure">血压</option>
                <option value="heartRate">心率</option>
                <option value="sleepQuality">睡眠</option>
              </select>
            </div>

            {/* 根据记录类型显示不同的表单字段 */}
            <div>
              <label className="block text-sm font-medium mb-2">记录详情</label>
              {renderRecordFields()}
            </div>

            {/* 备注 */}
            <div>
              <label className="block text-sm font-medium mb-2">备注</label>
              <textarea
                value={record.remark || ""}
                onChange={(e) => onChange({ ...record, remark: e.target.value })}
                className="w-full px-3 py-2 border rounded-lg bg-background min-h-[100px]"
                placeholder="添加备注..."
              />
            </div>

            {/* 按钮组 */}
            <div className="flex justify-between gap-4 pt-4 border-t">
              <div className="text-sm text-muted-foreground">
                {isCreating && "已自动保存草稿"}
              </div>
              <div className="flex gap-4">
                <button
                  onClick={handleClose}
                  className="px-4 py-2 text-sm rounded-lg hover:bg-accent transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={handleSave}
                  className="px-6 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2"
                >
                  <Save className="w-4 h-4" />
                  保存
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 